package com.example.environmentset.interceptor;

import com.example.environmentset.service.PortSetService;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.net.URI;
import java.util.Map;

/**
 * @author fangyuan.xia
 * @since 2022-08-15
 */
@Slf4j
public class ServletContextFeignInterceptor implements RequestInterceptor {

    @Autowired
    private PortSetService portSetService;

    @Override
    public void apply(RequestTemplate template) {
        String originUrl = template.feignTarget().url() + template.path();
        URI uri = URI.create(originUrl);
        if (template.feignTarget().url().contains("99bill")) {
            Map<String, Integer> contextPortMap = portSetService.get();
            for (Map.Entry<String, Integer> stringIntegerEntry : contextPortMap.entrySet()) {
                if (uri.getPath().startsWith("/" + stringIntegerEntry.getKey())) {
                    template.target("http://localhost:" + stringIntegerEntry.getValue());
                    log.info("{} convertTo {}", originUrl, template.path());
                    break;
                }
            }
        }

    }
}
